//
//  MLWSearchBar.m
//  KITCHEN_STORIES
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 MLW. All rights reserved.
//

#import "MLWSearchBar.h"

@implementation MLWSearchBar

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc
{
    [_searchBar release];
    [super dealloc];
}


/**
 
 *----自定义的初始化方法-------*
 
 参数 1.  frame               坐标
 参数 2.  cornerRadius        圆角
 参数 3.  borderWidth         边框宽度
 参数 4.  backgroundColor     背景颜色
 参数 5.  borderColor         边框颜色
 
 retain self;
 */

#pragma mark -- 初始化
- (instancetype)initWithFrame:(CGRect)frame cornerRadius:(CGFloat)cornerRadius borderWidth:(NSInteger)borderWidth backgroundColor:(UIColor *)backgroundColor borderColor:(UIColor *)borderColor
{
    self = [super initWithFrame:frame];
    
    if (self) {
        
        //初始化搜索框:
        self.searchBar = [[UISearchBar alloc] initWithFrame:frame];
        
        self.searchBar.delegate = self;
        
        //设置背景图是为了去掉上下的黑线:
        self.searchBar.backgroundImage = [[UIImage alloc] init];
        
        //设置SearchBar的颜色主题为白色:
        self.searchBar.barTintColor = [UIColor whiteColor];
        
        self.cornerRadius = cornerRadius;
        self.borderWidth = borderWidth;
        self.borderColor = borderColor;
        self.backgroundColor = backgroundColor;
        
        [self addSubview:_searchBar];
        [_searchBar release];
        
    }
    
    
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.searchBar.placeholder = @"搜索";
    
    //通过KVC 的方式获取到 UISearchBar 的私有属性并赋值
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    
    if (searchField) {
        
        //设置搜索框的背景颜色:
        [searchField setBackgroundColor:self.backgroundColor];
        
        //设置搜索框圆角:
        searchField.layer.cornerRadius = self.cornerRadius;
        
        //设置搜索框边框颜色:
        searchField.layer.borderColor = self.borderColor.CGColor;
        
        //设置边框宽度:
        searchField.layer.borderWidth = self.borderWidth;
        
        searchField.layer.masksToBounds = YES;
    }
}

#pragma mark <UISearchBarDelegate>代理方法:
#pragma mark 搜索框开始编辑状态,获取第一响应者
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
}

#pragma mark -- 点击cancel 按钮,退出编辑状态

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    
    [searchBar setShowsCancelButton:NO animated:YES];
    
    [searchBar endEditing:YES];
}

///搜索点击方法:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.LXSearchDelegate beginSearchWithString:searchBar.text];
    
}




@end
